import { got } from 'got';
import crypto from 'node:crypto';

import { type ShlianluResponse } from './schema.js';

// 联麓SMS API端点
const endpoint = 'apis.shlianlu.com/sms/trade/template/send';

export async function sendSmsRequest(
  TemplateId: string,
  templateParameters: string[],
  phoneNumber: string,
  config: {
    MchId: string;
    AppId: string;
    Version: string;
    AppKey: string;
  }
) {
  const { MchId, AppId, Version, AppKey } = config;
  const TimeStamp = String(Date.now());

  // 构建请求参数
  const params: Record<string, string> = {
    AppId,
    MchId,
    Version,
    SignType: 'MD5',
    TemplateId,
    TimeStamp,
    Type: '3',
  };

  const Signature = crypto
    .createHash('md5')
    .update(
      Object.keys(params)
        .slice()
        .sort()
        .map((key) => `${key}=${params[key]}`)
        .join('&') + `&key=${AppKey}`
    )
    .digest('hex')
    .toUpperCase();

  // 预处理手机号，去空格和+86
  const last11Digits = phoneNumber.replaceAll(/\D/g, '').slice(-11);

  const isValid = /^1[3-9]\d{9}$/.test(last11Digits);
  if (!isValid) {
    throw new Error(`手机号格式错误: ${last11Digits}`);
  }

  // 发送请求
  return got.post<ShlianluResponse>(`https://${endpoint}`, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json;charset=utf-8',
    },
    json: {
      ...params,
      PhoneNumberSet: [last11Digits],
      TemplateParamSet: templateParameters,
      Signature,
    },
    responseType: 'json',
  });
}
